import DetailsHead from "@/components/detailsHead/Header";
import Layer from "@/components/detailsLayer/Layer";
import SimpleList from "@components/orderDetail/SimpleList.vue";
import UploadFileSelector from "@/components/advance/upload/UploadFileSelector.vue";
import Descriptions from "./Descriptions.vue";
import QuoteList from "./QuoteList.vue";
import PayType from "./PayType.vue";
import SurchargeFee from "./SurchargeFee.vue";
import TotalList from "./TotalList.vue";
import QuoteMatchingDetail from "./QuoteMatchingDetail.vue"
import TransportQuote from "./TransportQuote.vue";
import { quotation, transport, finance } from "@/api/index";
import { returnThousandDigit, volumeOrWeightConversion } from "@/libs/util.js";
import {
  transportQuoteInfoArr,
  QuoteCarrArr,
  QuoteCstArr,
  totalData,
} from "@components/orderDetail/orderData";
import { mapState } from "vuex";

export default {
  name: "quoteFreightDetail",
  components: {
    DetailsHead,
    Layer,
    TransportQuote,
    PayType,
    SurchargeFee,
    TotalList,
    SimpleList,
    QuoteList,
    Descriptions,
    QuoteMatchingDetail,
    UploadFileSelector
  },
  data () {
    return {
      api: quotation,
      photo: [], //附件
      transportQuoteInfoArr,
      totalData,
      wayBillInfo: {},
      files: [],
      waybillCache: {},
      pageType: null,
      btnGroup: [],
      quoteData: {},
      wayBillColumn: [],
      loading: false,
      priceList: [], //报价费用
      payList: [],
      surchargeFees: [], // 补充费用
      waybillMatchData: [],     // 合单匹配合约-合单费用
      pendingFee: 0,
      processedFee: 0,
      matchId: null,
      matchVisible: false,
      carrierExtraType: 0, // 是否是个体司机
      remarks: null
    };
  },
  computed: {
    ...mapState({
      tenantInfo: (state) => state.tenant.tenantInfo
    }),
    waybillType () {
      return this.wayBillInfo?.waybillType;
    },
    configData () {
      return this.waybillType === 10 ? QuoteCstArr : QuoteCarrArr;
    },
    paymentLabel () {
      return this.waybillType === 10 ? '收' : '付';
    },
    waybillId () {
      return this.$route.query?.id || this.$route.query?.waybillId;
    },
    printTemplate () {
      return this.tenantInfo?.config?.printTemplate || [];
    },
    // 有效打印路由
    effectivePaths () {
      return ['WaybillFeePrint'];
    },
    // 租户配置打印路由
    printPath () {
      const cstPrintName = 'customerWaybillFeeTemplate';
      const carrPrintName = 'carrierWaybillFeeTemplate';
      let path = null;
      let printName = this.waybillType === 20 ? carrPrintName : cstPrintName;
      this.printTemplate?.length && this.printTemplate.some((o) =>
        (path = printName === o.name ? o.value.split(";") : null)
      );
      if (path && path.length) {
        return this.effectivePaths.includes(path[0]) ? path[0] : 'WaybillFeePrint'
      }
      return 'WaybillFeePrint';
    },
    content () {
      const { customer, carrier } = this.wayBillInfo
      if (this.waybillType === 20) {
        if (carrier?.carrierType === 0) {
          return '线下'
        }
        if (carrier?.carrierType === 1 && carrier.carrierExtraType == 0) {
          return '线上'
        }
      } else {
        switch (customer?.showCustomerType) {
          case 0:
            return '线下';
          case 1:
            return '线上';
          default:
            return ''
        }
      }
      return ''
    },
    iconName () {
      const { customer, carrier } = this.wayBillInfo
      if (this.waybillType === 20) {
        if (carrier?.carrierType === 0) {
          return 'xianxia'
        }
        if (carrier?.carrierType === 1 && carrier.carrierExtraType == 0) {
          return 'xianshang'
        }
      } else {
        switch (customer?.showCustomerType) {
          case 0:
            return 'xianxia';
          case 1:
            return 'xianshang';
          default:
            return ''
        }
      }
      return ''
    }
  },
  created () {
    // 查询运单信息
    this.getTransportDetail();
    this.getCollectionInfo();
  },
  methods: {
    thousandDigit (value, digit) {
      return returnThousandDigit(value, digit)
    },
    // 获取运单信息
    async getTransportDetail () {
      let { data } = await transport.getDetail(this.waybillId);
      this.wayBillInfo = data;
      if (data?.waybillPrice && data?.waybillPrice?.quotationStatus) {
        this.priceList = [{ ...data.waybillPrice }]
        this.getValidQuote();
      } else {
        this.priceList = [{}]
      }
      // 运单计费模式为重量 计费单位为吨
      if (
        data.transportRequirement?.chargeMode === 1 &&
        data.transportRequirement?.pricingUnit === 2
      ) {
        data.waybillCache.calculateWeight = volumeOrWeightConversion(
          0,
          data.waybillCache.calculateWeight
        );
      }
      // 运单计费模式为体积 计费单位为升
      if (
        data.transportRequirement?.chargeMode === 2 &&
        data.transportRequirement?.pricingUnit === 4
      ) {
        data.waybillCache.calculateVolume = volumeOrWeightConversion(
          1,
          data.waybillCache.calculateVolume
        );
      }
      // 运输模式为整车 车型为其他车型
      if (
        data.transportRequirement?.transportMode === 2 &&
        data.transportRequirement?.vehicleLength === 999
      ) {
        data.transportRequirement.vehicleLength = "其他";
      }
      //附件
      if (data.attachments) this.photo = data.attachments.filter((x) => x.type === 2);
      this.waybillCache = data.waybillCache;
      this.quoteData = {
        contractNo: data.contractNo,
        createAt: data.createAt,
        orderNo: data.orderNo,
        createName: data.createBy.name,
        customerName: data.customer.showCustomerName,
        carrierName: data?.carrier?.carrierName,
        driverName: data?.carrier?.driverName
      };
      // 报价费用结构转换
      if (data.transportRequirement.transportMode === 1) {
        this.wayBillColumn.push({ label: "零担费", name: "divideFee", type: 'text' });
        if (data.transportRequirement.pick)
          this.wayBillColumn.push({ label: "提货费", name: "pickFee", type: 'text' });
        if (data.transportRequirement.deliver)
          this.wayBillColumn.push({ label: "送货费", name: "deliverFee", type: 'text' });
      } else {
        this.wayBillColumn.push({ label: "整车费", name: "wholeFee", type: 'text' });
      }
      if (data.transportRequirement.onLoad)
        this.wayBillColumn.push({ label: "装货费", name: "loadFee", type: 'text' });
      if (data.transportRequirement.offLoad)
        this.wayBillColumn.push({ label: "卸货费", name: "unloadFee", type: 'text' });
      if (data.transportRequirement.insure)
        this.wayBillColumn.push({ label: "保险费", name: "insureFee", type: 'text' });

      // 个体司机
      this.carrierExtraType = data?.carrier?.carrierExtraType;
      if (!this.carrierExtraType) {
        // 税费固定
        this.wayBillColumn.push({ label: "税费", name: "taxFee", type: 'text' });
      }
      if (data.waybillPrice?.minCost) {
        this.wayBillColumn.push({ label: "最低费用", name: "minCost", type: 'text' });
      }
      this.wayBillColumn.push({
        name: "surchargeFee",
        label: "补充费用",
        type: 'text'
      }, {
        name: "totalFee",
        label: "总费用",
        type: 'total'
      });
    },
    //获取有效报价详情
    async getValidQuote () {
      let { data } = await quotation.getValidWaybillQuotation(this.waybillId);
      if (data) {
        this.matchId = data?.matchId;
        let quoteTotal = 0;
        let surchargeTotal = 0;
        // 补充费用
        this.surchargeFees = data?.surchargeFees || [];
        this.surchargeFees.forEach((element) => {
          surchargeTotal += element.money || 0;
        });
        this.waybillMatchData = [{
          pickFee: data?.pickFee || 0, //提货费
          deliverFee: data?.deliverFee || 0, //送货费
          loadFee: data?.loadFee || 0, //装货费
          unloadFee: data?.unloadFee || 0, //卸货费
          insureFee: data?.insureFee || 0, //保险费
          taxFee: data?.taxFee || 0, // 税费
          minCost: data?.minimumFee || 0 //最低费用
        }];
        // transportMode 1零担 2整车
        if (this.wayBillInfo.transportRequirement.transportMode === 1) {
          this.waybillMatchData[0].divideFee = data?.transportFee || 0;
        } else {
          this.waybillMatchData[0].wholeFee = data?.transportFee || 0;
        }
        if (data?.minimumFee) {
          quoteTotal = data.minimumFee + data?.taxFee || 0 + data?.insureFee || 0
        } else {
          // 计算运单费用总和
          for (let key in this.waybillMatchData[0]) {
            quoteTotal += this.waybillMatchData[0][key];
          }
        }
        this.waybillMatchData[0].quoteTotal = Number(quoteTotal.toFixed(2))
        this.waybillMatchData[0].surchargeFee = Number(surchargeTotal.toFixed(2))
        this.waybillMatchData[0].totalFee = returnThousandDigit(quoteTotal + surchargeTotal, 2)
        // 付款方式
        this.payList = [{ ...data }];
        this.remarks = data?.remarks;
      }
    },
    // 获取收款信息
    async getCollectionInfo () {
      let { data } = await finance.getCollectionInfo(this.waybillId);
      this.pendingFee = data?.pendingFee ? returnThousandDigit(data?.pendingFee, 2) : 0
      this.processedFee = data?.processedFee ? returnThousandDigit(data?.processedFee, 2) : 0
    }
  }
};
